package ru.hh.school;

import java.util.*;

public class Room {
    private String name;
    private Set<User> users;

    public Room(String name) {
        this.name = name;
        this.users = new HashSet<User>();
    }

    public String getName() {
        return name;
    }

    public void addUser(User user) {
        synchronized (users) {
            users.add(user);
        }
    }

    public void delUser(User user) {
        synchronized (users) {
            users.remove(user);
        }
    }

    public void send(String message) {
        List<User> shuffledUsers;
        synchronized (users) {
            shuffledUsers = new ArrayList<User>(users);
        }
        Collections.shuffle(shuffledUsers);
        for (User user : shuffledUsers) {
            user.sendMessage(message);
        }
    }

    public void send(String message, User exclude) {
        List<User> shuffledUsers;
        synchronized (users) {
            shuffledUsers = new ArrayList<User>(users);
        }
        Collections.shuffle(shuffledUsers, new Random(System.currentTimeMillis()));
        for (User user : shuffledUsers) {
            if (!user.equals(exclude)) {
                user.sendMessage(message);
            }
        }
    }

    public String toString() {
        return getName();
    }

}
